<?php

class Application_Model_MyCommonsMapper {

    protected $_dbTable;

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }

        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }

        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_MyCommons');
        }

        return $this->_dbTable;
    }

    public function save(Application_Model_MyCommons $commons) {
        $data = array(
            'Type' => $commons->getType(),
            'Name' => $commons->getName()
        );

        if (null === ($id = $commons->getId())) {
            unset($data['Id']);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('Id = ?' => $id));
        }
    }

    public function find($id, Application_Model_MyCommons $content) {
        $result = $this->getDbTable()->find($id);

        if (0 == count($result)) {
            return;
        }

        $row = $result->current();
        $content->setId($row->Id)
                ->setType($row->Type)
                ->setCat_id($row->Name);
    }

    public function fetchAll($query = null) {
        $table = $this->getDbTable();
        $select = $table->select();
        $select->from($table)
                ->order("Name asc");
        if (!($query == null)) {
            $select->where($query);
        }
        $select->order("Id asc");

        $resultSet = $table->fetchAll($select);
        return $this->processResultSet($resultSet);
    }

    private function processResultSet($resultSet) {
        $entries = array();

        foreach ($resultSet as $row) {
            $entry = new Application_Model_MyCommons();

            $entry->setId($row->Id);
            $entry->setType($row->Type);
            $entry->setName($row->Name);

            $entries[] = $entry;
        }

        return $entries;
    }

    public function getCount() {
        $table = $this->getDbTable();
        $select = $table->select();
        $select->from($table, array("count(Id) as sum"));

        $resultSet = $table->fetchAll($select);
        $array = $resultSet->toArray();

        return $array[0]['sum'];
    }

    public function fetchAllFilterToArray($query) {
        $table = $this->getDbTable();
        $select = $table->select();

        $select->from($table)
                ->where($query);

        $resultSet = $table->fetchAll($select);
        $toArray = $resultSet->toArray();

        return $toArray[0];
    }

    public function delete($id) {
        $table = $this->getDbTable();
        $table->delete("Id = $id");
    }

}